ringbuf
Lock-free SPSC FIFO ring buffer with direct access to inner data.
Features
- Lock-free operations - they succeed or fail immediately without blocking or waiting.
- Arbitrary item type (not only
Copy
). - Items can be inserted and removed one by one or many at once.
- Thread-safe direct access to the internal ring buffer memory.
Read
andWrite
implementation.- Overwriting mode support.
- Can be used without
std
and even withoutalloc
(using only statically-allocated memory). - Experimental
async
/.await
support.
Usage
At first you need to create the ring buffer itself. HeapRb
is recommended but you may choose another one.
After the ring buffer is created it may be splitted into pair of Producer
and Consumer
.
Producer
is used to insert items to the ring buffer, Consumer
- to remove items from it.
For SharedRb
and its derivatives they can be used in different threads.
Types
There are several types of ring buffers provided:
LocalRb
. Only for single-threaded use.SharedRb
. Can be shared between threads. Its derivatives:HeapRb
. Contents are stored in dynamic memory. Recommended for use in most cases.StaticRb
. Contents can be stored in statically-allocated memory.
Performance
SharedRb
needs to synchronize CPU cache between CPU cores. This synchronization has some overhead.
To avoid multiple unnecessary synchronizations you may use postponed mode of operation (see description for Producer
and Consumer
)
or methods that operates many items at once (Producer::push_slice
/Producer::push_iter
, Consumer::pop_slice
, etc.).
For single-threaded usage LocalRb
is recommended because it is faster than SharedRb
due to absence of CPU cache synchronization.
Benchmarks
You may see typical performance of different methods in benchmarks:
Nightly toolchain is required.
Examples
Simple
use HeapRb;
#
No heap
use StaticRb;
#
Overwrite
Ring buffer can be used in overwriting mode when insertion overwrites the latest element if the buffer is full.
use ;
#
Note that push_overwrite
requires exclusive access to the ring buffer
so to perform it concurrently you need to guard the ring buffer with Mutex
or some other lock.
async
/.await
There is an experimental crate async-ringbuf
which is built on top of ringbuf
and implements asynchronous ring buffer operations.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.